from django.shortcuts import render,redirect,reverse,HttpResponse
from app01 import models
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
# Create your views here.
import re

class Userforms(forms.Form):
    def clean_username(self):
        value=self.cleaned_data.get("username")
        if models.User.objects.filter(user=value):
            raise ValidationError("用户名已存在")
        return value
    def clean(self):
        pwd=self.cleaned_data.get("password")
        re_pwd=self.cleaned_data.get("re_password")
        if pwd == re_pwd:
            return self.cleaned_data
        else:
            self.add_error("re_password","两次密码不一致！")
            raise ValidationError("两次密码不一致")
    username=forms.CharField(max_length=12,min_length=5,label="用户名:",error_messages={'required': '不能为空', 'invalid': '格式错误'})
    name=forms.CharField(label="姓名:",error_messages={'required': '不能为空'})
    password = forms.CharField(min_length=6,
                               label="密码:",
                               required=True,
                               widget=forms.PasswordInput,
                               error_messages={'requirec': '不能为空', 'invalid': '格式错误',
                                               "min_length": "密码最短6位"}
                               )
    re_password=forms.CharField(min_length=6,
                               label="确认密码:",
                               required=True,
                               widget=forms.PasswordInput,
                               error_messages={'requirec': '不能为空', 'invalid': '格式错误',
                                               "min_length": "密码最短6位"}
                               )
    phone=forms.CharField(max_length=11,min_length=11,label="手机号：",error_messages={'requirec':'不能为空', 'invalid': '格式错误',},validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格式不正确')])


class Labforms(forms.Form):
    def clean_lname(self):
        value=self.cleaned_data.get("lname")
        if models.Lab.objects.filter(l_name=value):
            raise ValidationError("名称已存在")
        return value
    def clean_roomnum(self):
        value=self.cleaned_data.get("roomnum")
        value = int(value)
        if models.Lab.objects.filter(room_number=value):
            raise ValidationError("房间号已存在")
        return value

    lname = forms.CharField(label="实验室名称:",error_messages={'required': '不能为空', 'invalid': '格式错误'})
    fool=forms.CharField(label="楼层:",error_messages={'required': '不能为空', 'invalid': '格式错误'})
    roomnum=forms.CharField(label="房间号:",error_messages={'required': '不能为空', 'invalid': '格式错误'})
    user=forms.MultipleChoiceField(choices=models.User.objects.all().values_list("pk","u_name"),label="负责人:",error_messages={'required': '不能为空', 'invalid': '格式错误'})

class Propertyforms(forms.Form):
    def clean_pname(self):
        value=self.cleaned_data.get("pname")
        if models.Property.objects.filter(P_name=value):
            raise ValidationError("名称已存在")
        return value


    pname = forms.CharField(label="物资名称:",error_messages={'required': '不能为空', 'invalid': '格式错误'})
    date=forms.CharField(label="购买时间:",error_messages={'required': '不能为空', 'invalid': '格式错误'})
    describe=forms.CharField(label="物品描述:",error_messages={'required': '不能为空', 'invalid': '格式错误'})
    user=forms.MultipleChoiceField(choices=models.User.objects.all().values_list("pk","u_name"),label="购买人:",error_messages={'required': '不能为空', 'invalid': '格式错误'})
    labs = forms.MultipleChoiceField(choices=models.Lab.objects.all().values_list("pk", "l_name"), label="所属实验室:",
                                     error_messages={'required': '不能为空', 'invalid': '格式错误'})
def user_list(request):
    obj=models.User.objects.all()
    return render(request,"user_list.html",{'obj':obj})
def lab_list(request):
    obj=models.Lab.objects.all()
    return render(request, "lab_list.html", {'obj': obj })
def property_list(request):
    obj=models.Property.objects.all()
    return render(request,"property_list.html",{'obj':obj})

def user_add(request):
    if request.method=="POST":
        obj = Userforms(request.POST)
        if obj.is_valid():
            models.User.objects.create(u_name=request.POST.get("name"),user=request.POST.get("username"),pwd=request.POST.get("password"),phone=request.POST.get("phone"))
            return redirect(reverse("user_list"))
    else:
        obj=Userforms()
    return render(request,"user_add.html",{"obj":obj})

def lab_add(request):
    if request.method=="POST":
        obj = Labforms(request.POST)
        if obj.is_valid():
            data=request.POST
            lab_obj=models.Lab.objects.create(l_name=data.get("lname"),floor=data.get("fool"),room_number=data.get("roomnum"))
            lab_obj.user.set(data.getlist("user"))
            return redirect(reverse("lab_list"))
    else:
        obj=Labforms()
    return render(request,"lab_add.html",{"obj":obj})

def property_add(request):
    if request.method=="POST":
        obj = Propertyforms(request.POST)
        if obj.is_valid():
            data=request.POST
            property_obj=models.Property.objects.create(P_name=data.get("pname"),times=data.get("date"),describe=data.get("describe"))
            property_obj.user.set(data.getlist("user"))
            property_obj.lab_set.set(data.getlist("labs"))
            return redirect(reverse("property_list"))
    else:
        obj=Propertyforms()
    return render(request,"property_add.html",{"obj":obj})


def user_alter(request,pk):
    error=""
    perror=""
    obj = models.User.objects.filter(pk=pk).first()
    if request.method=="POST":
        u_name=request.POST.get("u_name")
        user=request.POST.get("user")
        pwd=request.POST.get("pwd")
        phone=request.POST.get("phone")
        if user != obj.user and models.User.objects.filter(user=user):
            error="修改的用户名已存在"
        elif (not re.findall('^1[3-9]\d{9}$',phone)) or  phone != obj.phone and models.User.objects.filter(phone=phone):
            perror="修改手机号格式错误或已存在"
        else:
            models.User.objects.filter(pk=pk).update(user=user,u_name=u_name,pwd=pwd,phone=phone)
            return redirect(reverse("user_list"))

    return render(request,"user_alter.html",{"obj":obj,'error':error,"perror":perror})


def lab_alter(request,pk):
    global error
    obj=models.Lab.objects.filter(pk=pk).first()
    error = ""
    rerroe = ""
    if request.method=="POST":
        l_name=request.POST.get("l_name")
        floor=request.POST.get("floor")
        room=request.POST.get("room")
        if not l_name :
            error="名称不能为空"
        elif l_name != obj.l_name and models.Lab.objects.filter(l_name=l_name):
            error="修改名称存在"
        elif int(room) != obj.room_number and models.Lab.objects.filter(room_number=room):
            rerroe="修改的放间号已存在"

        else:
            l_obj=models.Lab.objects.filter(pk=pk)
            l_obj.update(l_name=l_name,room_number=room,floor=floor)

            obj.user.set(request.POST.getlist("abc"))
            return redirect(reverse("lab_list"))
    u_obj=models.User.objects.all()
    return render(request,"lab_alter.html",{"obj":obj,"u_obj":u_obj,"error":error,"rerroe":rerroe})


def property_alter(request,pk):
    error=""
    obj=models.Property.objects.filter(pk=pk).first()
    if request.method == "POST":
        p_name = request.POST.get("p_name")
        times = request.POST.get("times")
        describe = request.POST.get("describe")

        if p_name != obj.P_name and models.Property.objects.filter(P_name=p_name):
            error = "修改的物品名称已存在"
        elif not p_name:
            error="修改的名称不能为空"
        else:
            models.Property.objects.filter(pk=pk).update(P_name=p_name, times=times, describe=describe)
            obj.user.set(request.POST.getlist("abc"))
            obj.lab_set.set(request.POST.getlist("labs"))
            return redirect(reverse("property_list"))

    l_obj=models.Lab.objects.all()
    u_obj=models.User.objects.all()

    return render(request,"property_alter.html",{"obj":obj,"l_obj":l_obj,"u_obj":u_obj,"error":error})



def dels(request):
    a=request.GET.get("obj")
    a=a.split(" ")[0]
    id=request.GET.get("pk")
    obj=getattr(models,a)
    a_obj=obj.objects.filter(id=id)
    if not a_obj:
        ret=False
        return HttpResponse(ret)
    a_obj.delete()
    ret=True

    return HttpResponse(ret)